package com.excellent.auth.controller;

import com.excellent.auth.config.JwtProperties;
import com.excellent.auth.service.AuthService;
import com.excellent.common.utils.CookieUtils;
import com.excellent.pojo.UserInfo;
import com.excellent.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 授权中心进行用户校验
 * @author Xxacker
 */
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录授权
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response) {
        // 登录校验
        String token = this.authService.authentication(username, password);
        if (StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);    //身份未认证
        }
        // 通过 request 和 response ，将 token 写入 cookie,并指定 httpOnly 为 true，防止通过 JS 获取和修改
        // 在其他微服务中也可以通过 getCookie 来解析 cookie
        CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getCookieMaxAge()*60, null, true);
        return ResponseEntity.ok().build();
    }

    /**【首页-页面顶部用户登录后，信息显示】
     * 验证用户信息
     * @CookieValue 接收数据的方式
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(@CookieValue("EX_TOKEN")String token, HttpServletRequest request, HttpServletResponse response){
        try {
            // 通过 jwt 的工具类使用公钥解析 jwt，从 token 中解析 “用户” 信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
            if (userInfo == null){
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            // 解析成功要重新刷新 token
            token = JwtUtils.generateToken(userInfo, this.jwtProperties.getPrivateKey(), this.jwtProperties.getExpire());
            // 更新 cookie 中的 token
            CookieUtils.setCookie(request, response, this.jwtProperties.getCookieName(), token, this.jwtProperties.getCookieMaxAge() * 60);

            // 解析成功返回用户信息
            System.out.println(ResponseEntity.ok(userInfo));
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 出现异常则，响应500
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

}
